import { Component, OnInit } from '@angular/core'
import { JsonApiService } from 'app/core/api/json-api.service' //http请求配置引入
import { Router, ActivatedRoute } from '@angular/router' //路由引入
import { config } from '../../shared/smartadmin.config'
import 'assets/js/bootstrap-switch.min.js'
import 'assets/css/bootstrap-switch.min.css'

declare var $: any
declare var Viewer: any
@Component({
  selector: 'sa-contract-config',
  templateUrl: './contract-config.component.html',
  styleUrls: ['./contract-config.component.css']
})
export class ContractConfigComponent implements OnInit {
  tableData: any = [] //table数据
  totalCount: number = 0 //分页总条数
  curPage: number = 1 //分页当前页
  pageSize: number = 10 //内置的分页每页条数
  formType: string = 'add' // 新增
  renewalCostList: any = [] // 服务费的数组
  dockingCostList: any = [] // 对接费的数组
  firstCostEntities: any = [] // 首次安装费数组
  initDateRange: any = {
    startTime: '',
    endTime: ''
  } // 时间组件需要渲染的值
  tableParam: any = {
    companyId: '',
    companyName: '',
    scenarioName: '',
    dateType: '1',
    sortType: '1',
    status: ''
    //	    startTime: '',
    //	    endTime: '',
    //	    searchKey: '',//搜索keyword
  }
  constructor(private jsonApiService: JsonApiService, private router: Router, private activatedRoute: ActivatedRoute) {
    activatedRoute.queryParams.subscribe(queryParams => {
      this.curPage = queryParams.nowPage || 1
    })
  }
  validatorOptions = {
    excluded: [':disabled'],
    feedbackIcons: {
      valid: 'glyphicon glyphicon-ok',
      invalid: 'glyphicon glyphicon-remove',
      validating: 'glyphicon glyphicon-refresh'
    },
    fields: {
      scenarioName: {
        validators: {
          notEmpty: {
            message: '请输入方案名称'
          }
        }
      },
      companyName: {
        trigger: 'change',
        validators: {
          notEmpty: {
            message: '请选择方案适用范围'
          }
        }
      },
      firstCost: {
        validators: {
          notEmpty: {
            message: '请首输入次安装价格'
          }
        }
      }
      //   renewalCost: {
      //     validators: {
      //       notEmpty: {
      //         message: '请输入服务续费价格'
      //       }
      //     }
      //   },
      //   renewalCostMonth: {
      //     validators: {
      //       notEmpty: {
      //         message: '请输入续费时长'
      //       }
      //     }
      //   },
      //   dockingCost: {
      //     validators: {
      //       notEmpty: {
      //         message: '请输入对接费用价格'
      //       }
      //     }
      //   },
      //   dockingCostMonth: {
      //     validators: {
      //       notEmpty: {
      //         message: '请输入对接时长'
      //       }
      //     }
      //   }
    }
  }
  ngOnInit() {
    this.initSwitch()
    this.load()
  }
  // 接收子组件传递过来的数据
  getSelectTableTime(time) {
    this.tableParam.startTime = time.startTime
    this.tableParam.endTime = time.endTime
  }
  // 公司选中回调
  companySelected(data) {
    this.tableParam.companyId = data.companyId
    this.tableParam.companyName = data.companyName
  }
  //表格搜索
  table_search() {
    this.curPage = 1
    this.tableParam.searchKey = common.stringTrim(this.tableParam.searchKey)
    this.load()
  }
  //刷新
  refresh() {
    this.load()
  }
  //初始化加载list数据
  load() {
    let data = {
      pageSize: this.pageSize,
      nowPage: this.curPage,
      parameters: {
        companyId: this.tableParam.companyId,
        scenarioName: this.tableParam.scenarioName.trim(),
        dateType: this.tableParam.dateType,
        sortType: this.tableParam.sortType,
        status: this.tableParam.status
        //				startTime:this.tableParam.startTime,
        //				endTime:this.tableParam.endTime,
        //				searchKey:this.tableParam.searchKey,
      }
    }
    let reqdata = 'gridPager=' + JSON.stringify(data)
    this.jsonApiService.http('contractV2/contractList.html', reqdata).subscribe(data => {
      this.tableData = data.exhibitDatas
      this.totalCount = data.recordCount
    })
  }
  //分页回调
  paginate(e) {
    this.curPage = e.page + 1
    this.pageSize = e.rows
    this.load()
  }
  /**
   *   项目事件新增编辑模块===========================================================================================
   */
  installTax = [
    {
      taxPrice: '',
      name: '通信终端设备*车载智能终端',
      tax: ''
    },
    {
      taxPrice: '',
      name: '信息技术服务*车载称重服务',
      tax: ''
    }
  ]
  contractFormBack = {
    id: '',
    scenarioName: '',
    companyArrays: [],
    companyName: '',
    companyId: '',
    status: 0,
    firstCost: '',
    renewalCost: '',
    renewalMonth: '',
    outsideCost: '',
    outsideMonth: '',
    electronicContract: 1,
    auth: 1,
    firstModelUrl: '',
    isOpenInstallTax: 0,
    isOpenMaintainTax: 0,
    isOpenServiceTax: 0,
    // installTax: this.installTax, //安装费税务信息
    firstCostEntities: [
      {
        firstCost: '',
        installTax: this.installTax
      }
    ],
    maintainTax: {
      name: '信息技术服务*车载称重服务(维修)',
      tax: ''
    }, //维修费税务信息
    serviceTax: {
      name: '信息技术服务*车载称重服务',
      tax: ''
    }, //续费/对接费税务信息
    renewalModelUrl: ''
  }

  contractForm: any = this.deepClone(this.contractFormBack)
  modelType: string = '1'
  addCompanySelected(data) {
    this.contractForm.companyId = data.companyIdSelectedList.join(',')
    this.contractForm.companyName = data.companyNameSelectedList.join(',')
  }
  initSwitch() {
    var that = this
    $('.isStatus').bootstrapSwitch('destroy')
    $('.isStatus').bootstrapSwitch({
      //初始化按钮
      onText: '开启',
      offText: '关闭',
      onColor: 'primary',
      offColor: 'warning',
      onSwitchChange: function (event, state) {
        that.contractForm[event.target.name] = state ? 1 : 0
      }
    })
  }
  // 点击新增首次安装费
  addInstallation() {
    this.firstCostEntities.push({
      firstCost: '',
      installTax: [
        {
          taxPrice: '',
          name: '通信终端设备*车载智能终端',
          tax: ''
        },
        {
          taxPrice: '',
          name: '信息技术服务*车载称重服务',
          tax: ''
        }
      ]
    })
  }

  // 确认提交时候 检查 首次安装价格
  checkFirstCostRule(firstCostEntities: any[]) {
    let result = {
      status: true,
      message: '',
      firstCostEntities: []
    }
    const list = []
    for (let i = 0; i < firstCostEntities.length; i++) {
      const firstCost: any = firstCostEntities[i].firstCost ? Number(firstCostEntities[i].firstCost) : ''
      if (firstCost <= 0) {
        result.status = false
        result.message = `<${i + 1}>首次安装价格不允许小于等于0`
        return result
      }
      const installTax: any = firstCostEntities[i].installTax
      if (this.contractForm.isOpenInstallTax === 1) {
        let taxPrice1: number = installTax[0].taxPrice ? Number(installTax[0].taxPrice) : 0
        let taxPrice2: number = installTax[1].taxPrice ? Number(installTax[1].taxPrice) : 0
        taxPrice1 = taxPrice1 ? parseInt(String(taxPrice1 * 100)) : 0
        taxPrice2 = taxPrice1 ? parseInt(String(taxPrice2 * 100)) : 0
        if (taxPrice1 + taxPrice2 !== parseInt(String(firstCost * 100))) {
          result.status = false
          result.message = `<${i + 1}>中${installTax[0].name}加上${installTax[1].name}不等于首次安装价格`
          return result
        }
        if (installTax[0].taxPrice > 0 && !installTax[0].tax) {
          result.status = false
          result.message = `<${i + 1}>中${installTax[0].name}开票税率不能为空`
          return result
        }
        if (installTax[1].taxPrice > 0 && !installTax[1].tax) {
          result.status = false
          result.message = `<${i + 1}>中${installTax[1].name}开票税率不能为空`
          return result
        }
      }
      list.push({
        firstCost: parseInt(String(firstCost * 100)),
        installTax: [
          {
            name: installTax[0].name,
            taxPrice: installTax[0].taxPrice ? parseInt(String(installTax[0].taxPrice * 100)) : '',
            tax: installTax[0].tax,
            taxCode: installTax[0].taxCode ? installTax[0].taxCode : undefined
          },
          {
            name: installTax[1].name,
            taxPrice: installTax[1].taxPrice ? parseInt(String(installTax[1].taxPrice * 100)) : '',
            tax: installTax[1].tax,
            taxCode: installTax[1].taxCode ? installTax[1].taxCode : undefined
          }
        ]
      })
    }
    result.firstCostEntities = list
    return result
  }

  // 点击删除首次安装费
  deleteInstallation(index) {
    this.firstCostEntities.splice(index, 1)
  }

  // 首次安装价格改变
  firstCostChange(value, index) {
    this.firstCostEntities[index].firstCost = value
  }

  // 开票金额改变
  taxPriceChange(value, index, priceIndex) {
    this.firstCostEntities[index].installTax[priceIndex].taxPrice = value
  }

  // 开票税率改变
  taxChange(value, index, taxIndex) {
    this.firstCostEntities[index].installTax[taxIndex].tax = value
  }

  // 点击加号触发的回调
  addMaterial(type) {
    if (type == 1) {
      if (this.renewalCostList.length > 11) return
      this.renewalCostList.push({
        costMonth: '',
        costAccount: ''
      })
    } else if (type == 2) {
      if (this.dockingCostList.length > 11) return
      this.dockingCostList.push({
        costMonth: '',
        costAccount: ''
      })
    }
  }

  // 点击删除的触发的回调
  deleteMaterial(type, index) {
    if (type == 1) {
      this.renewalCostList.splice(index, 1)
    } else if (type == 2) {
      this.dockingCostList.splice(index, 1)
    }
  }

  contentChange(value, index, str, type) {
    if (type === 1) {
      this.renewalCostList[index][str] = value
    } else if (type === 2) {
      this.dockingCostList[index][str] = value
    }
  }

  // 添加项目事件界面打开
  showAddUserModal(modal) {
    if (this.isViewer && $('.viewer-container').length > 0) {
      this.viewer.destroy()
    }
    modal.show()
    $('#projectEventForm').data('bootstrapValidator').resetForm()
    this.formType = 'add'
    let that = this
    this.imageInfo = {
      imageList: [],
      firstModelUrl: [],
      renewalModelUrl: [],
      describe: '合同模板'
    }
    this.renewalCostList = [
      {
        costMonth: '',
        costAccount: ''
      }
    ]
    this.dockingCostList = [
      {
        costMonth: '',
        costAccount: ''
      }
    ]
    this.firstCostEntities = [
      {
        firstCost: '',
        installTax: [
          {
            taxPrice: '',
            name: '通信终端设备*车载智能终端',
            tax: ''
          },
          {
            taxPrice: '',
            name: '信息技术服务*车载称重服务',
            tax: ''
          }
        ]
      }
    ]
    this.contractForm = this.deepClone(this.contractFormBack)

    setTimeout(() => {
      that.initSwitch()
    }, 10)
    // $('.isStatus').bootstrapSwitch('state', false)
  }
  // 编辑项目事件
  editRow(row, modal, type) {
    if (this.isViewer && $('.viewer-container').length > 0) {
      this.viewer.destroy()
    }
    var that = this
    modal.show()
    $('#projectEventForm').data('bootstrapValidator').resetForm()
    this.formType = type
    row = JSON.parse(JSON.stringify(row))
    console.log(row)

    for (let key in this.contractForm) {
      this.contractForm[key] = row[key]
    }
    const _firstCostEntities = []
    if (row.firstCostEntities) {
      row.firstCostEntities.forEach(item => {
        let installTax = item.installTax
        if (!installTax || installTax.length < 1) {
          installTax = [
            {
              taxPrice: '',
              name: '通信终端设备*车载智能终端',
              tax: ''
            },
            {
              taxPrice: '',
              name: '信息技术服务*车载称重服务',
              tax: ''
            }
          ]
        }
        _firstCostEntities.push({
          firstCost: item.firstCost / 100,
          installTax: [
            {
              name: installTax[0].name,
              taxPrice: installTax[0].taxPrice ? installTax[0].taxPrice / 100 : '',
              tax: installTax[0].tax
            },
            {
              name: installTax[1].name,
              taxPrice: installTax[1].taxPrice ? installTax[1].taxPrice / 100 : '',
              tax: installTax[1].tax
            }
          ]
        })
      })
    } else {
      _firstCostEntities.push({
        firstCost: '',
        installTax: [
          {
            taxPrice: '',
            name: '通信终端设备*车载智能终端',
            tax: ''
          },
          {
            taxPrice: '',
            name: '信息技术服务*车载称重服务',
            tax: ''
          }
        ]
      })
    }
    this.firstCostEntities = _firstCostEntities

    if (!row.isOpenMaintainTax) {
      this.contractForm.maintainTax = this.deepClone(this.contractFormBack.maintainTax)
    }

    if (!row.isOpenServiceTax) {
      this.contractForm.serviceTax = this.deepClone(this.contractFormBack.serviceTax)
    }

    if (row.renewalCostList && row.renewalCostList.length > 0) {
      this.renewalCostList = row.renewalCostList.map(item => {
        item.costAccount = item.costAccount / 100
        return item
      })
    } else {
      this.renewalCostList = [
        {
          costMonth: '',
          costAccount: ''
        }
      ]
    }

    if (row.dockingCostList && row.dockingCostList.length > 0) {
      this.dockingCostList = row.dockingCostList.map(item => {
        item.costAccount = item.costAccount / 100
        return item
      })
    } else {
      this.dockingCostList = [
        {
          costMonth: '',
          costAccount: ''
        }
      ]
    }

    this.contractForm.firstCost = this.contractForm.firstCost / 100
    this.contractForm.renewalCost = this.contractForm.renewalCost / 100
    this.contractForm.outsideCost = this.contractForm.outsideCost / 100
    this.imageInfo = {
      imageList: [],
      firstModelUrl: [],
      renewalModelUrl: [],
      describe: '合同模板'
    }
    //显示图片
    if (row.firstModelUrl) {
      this.imageInfo.firstModelUrl.push(row.firstModelUrl)
    }
    if (row.renewalModelUrl) {
      this.imageInfo.renewalModelUrl.push(row.renewalModelUrl)
    }
    setTimeout(() => {
      that.initSwitch()
    }, 10)
  }
  viewRow(row, modal, type) {
    if (this.isViewer && $('.viewer-container').length > 0) {
      this.viewer.destroy()
    }
    modal.show()
    this.formType = type
    row = JSON.parse(JSON.stringify(row))
    for (let key in this.contractForm) {
      this.contractForm[key] = row[key]
    }

    // if (row.isOpenInstallTax) {
    //   this.contractForm.installTax = row.installTax.map(item => {
    //     if (item.taxPrice) {
    //       item.taxPrice = item.taxPrice / 100
    //     } else {
    //       item.taxPrice = ''
    //     }
    //     return item
    //   })
    // } else {
    //   this.contractForm.installTax = this.installTax
    // }

    const _firstCostEntities = []
    if (row.firstCostEntities) {
      row.firstCostEntities.forEach(item => {
        let installTax = item.installTax
        if (!installTax || installTax.length < 1) {
          installTax = [
            {
              taxPrice: '',
              name: '通信终端设备*车载智能终端',
              tax: ''
            },
            {
              taxPrice: '',
              name: '信息技术服务*车载称重服务',
              tax: ''
            }
          ]
        }
        _firstCostEntities.push({
          firstCost: item.firstCost / 100,
          installTax: [
            {
              name: installTax[0].name,
              taxPrice: installTax[0].taxPrice ? installTax[0].taxPrice / 100 : '',
              tax: installTax[0].tax
            },
            {
              name: installTax[1].name,
              taxPrice: installTax[1].taxPrice ? installTax[1].taxPrice / 100 : '',
              tax: installTax[1].tax
            }
          ]
        })
      })
    } else {
      _firstCostEntities.push({
        firstCost: '',
        installTax: [
          {
            taxPrice: '',
            name: '通信终端设备*车载智能终端',
            tax: ''
          },
          {
            taxPrice: '',
            name: '信息技术服务*车载称重服务',
            tax: ''
          }
        ]
      })
    }
    this.firstCostEntities = _firstCostEntities

    if (!row.isOpenMaintainTax) {
      this.contractForm.maintainTax = this.deepClone(this.contractFormBack.maintainTax)
    }

    if (!row.isOpenServiceTax) {
      this.contractForm.serviceTax = this.deepClone(this.contractFormBack.serviceTax)
    }

    if (row.renewalCostList && row.renewalCostList.length > 0) {
      this.renewalCostList = row.renewalCostList.map(item => {
        item.costAccount = item.costAccount / 100
        return item
      })
    } else {
      this.renewalCostList = [
        {
          costMonth: '',
          costAccount: ''
        }
      ]
    }

    if (row.dockingCostList && row.dockingCostList.length > 0) {
      this.dockingCostList = row.dockingCostList.map(item => {
        item.costAccount = item.costAccount / 100
        return item
      })
    } else {
      this.dockingCostList = [
        {
          costMonth: '',
          costAccount: ''
        }
      ]
    }

    let tenArr1: any = [],
      tenArr2: any = []
    for (let item of this.contractForm.companyArrays) {
      tenArr1.push(item.companyName)
      tenArr2.push(item.companyId)
    }
    this.contractForm.companyName = tenArr1.join(',')
    this.contractForm.companyId = tenArr2.join(',')
    this.contractForm.firstCost = this.contractForm.firstCost / 100
    this.contractForm.renewalCost = this.contractForm.renewalCost / 100
    this.contractForm.outsideCost = this.contractForm.outsideCost / 100
    this.imageInfo = {
      imageList: [],
      firstModelUrl: [],
      renewalModelUrl: [],
      describe: '合同模板'
    }
    //显示图片
    if (row.firstModelUrl) {
      this.imageInfo.firstModelUrl.push(row.firstModelUrl)
    }
    if (row.renewalModelUrl) {
      this.imageInfo.renewalModelUrl.push(row.renewalModelUrl)
    }
  }
  // 添加项目事件关闭
  closeProjectEventModal(modal) {
    this.dockingCostList = []
    this.renewalCostList = []
    $('#projectEventForm').data('bootstrapValidator').resetForm()
    modal.hide()
  }

  // 判断相同月份的前提下续费价格是否有重复
  isRepeatPrice(data) {
    const monthCostMap = new Map()
    for (const item of data) {
      const costMonth = Number(item.costMonth)
      const costAccount = Number(item.costAccount)

      if (!monthCostMap.has(costMonth)) {
        monthCostMap.set(costMonth, new Set())
      }

      const costs = monthCostMap.get(costMonth)

      if (costs.has(costAccount)) {
        return true
      }

      costs.add(costAccount)
    }

    return false
  }

  isRepeat(arr) {
    const hash = {}
    for (const i in arr) {
      const item = arr[i]
      const monthKey = item.costMonth
      const price = Number(item.costAccount)
      const hashItem = hash[monthKey]
      if (hashItem) {
        // 判断金额是否重复
        if (hashItem.includes(price)) {
          return true
        }
        hashItem.push(price)
      } else {
        // 没有数据写入
        hash[monthKey] = [price]
      }
    }
    return false
  }
  deepClone(obj) {
    let objClone = Array.isArray(obj) ? [] : {}
    if (obj && typeof obj === 'object') {
      for (let key in obj) {
        if (obj.hasOwnProperty(key)) {
          //判断ojb子元素是否为对象，如果是，递归复制
          if (obj[key] && typeof obj[key] === 'object') {
            objClone[key] = this.deepClone(obj[key])
          } else {
            //如果不是，简单复制
            objClone[key] = obj[key]
          }
        }
      }
    }
    return objClone
  }
  // 提交
  projectEventSubmit(modal) {
    $('#projectEventForm').bootstrapValidator('validate') //开启验证
    let isValid = $('#projectEventForm').data('bootstrapValidator').isValid() //验证是否通过
    if (isValid) {
      this.contractForm.firstModelUrl = this.imageInfo.firstModelUrl.join(',')
      this.contractForm.renewalModelUrl = this.imageInfo.renewalModelUrl.join(',')
      if (this.contractForm.electronicContract == '1') {
        if (!(this.contractForm.firstModelUrl && this.contractForm.renewalModelUrl)) {
          this.jsonApiService.message('请上传电子合同模板(首次安装模板+服务续费模板)')
          return
        }
      }
      if (this.isRepeatPrice(this.renewalCostList)) {
        this.jsonApiService.message('相同月份续费价格有重复，请重新输入')
        return
      }
      if (this.isRepeat(this.dockingCostList)) {
        this.jsonApiService.message('对接月份已有相同费用，请重新输入')
        return
      }
      let isEmptyRenewal = false
      let isValidRenewal = false
      let isRegRenewal = false
      const reg = new RegExp(/\d/)
      this.renewalCostList.map(item => {
        if (item.costAccount === '' || item.costMonth === '') {
          isEmptyRenewal = true
          return
        }
        if (item.costAccount < 0.01) {
          isValidRenewal = true
          return
        }
        if (!reg.test(item.costAccount) || !reg.test(item.costMonth)) {
          isRegRenewal = true
        }
      })

      if (isEmptyRenewal) {
        this.jsonApiService.message('续费时长或续费价格不能为空')
        return
      }
      if (isRegRenewal) {
        this.jsonApiService.message('续费时长或续费价格格式不正确')
        return
      }
      if (isValidRenewal) {
        this.jsonApiService.message('续费价格不能小于0.01')
        return
      }
      let isEmptyDocking = false
      let isValidDocking = false
      let isRegDocking = false
      this.dockingCostList.map(item => {
        if (item.costAccount === '' || item.costMonth === '') {
          isEmptyDocking = true
          return
        }
        if (item.costAccount < 0.1) {
          isValidDocking = true
          return
        }
        if (!reg.test(item.costAccount) || !reg.test(item.costMonth)) {
          isRegDocking = true
        }
      })
      if (isEmptyDocking) {
        this.jsonApiService.message('对接时长或对接价格不能为空')
        return
      }
      if (isRegDocking) {
        this.jsonApiService.message('对接时长或对接价格格式不正确')
        return
      }
      if (isValidDocking) {
        this.jsonApiService.message('对接价格不能小于0.1')
        return
      }
      const renewalCostListClone: any = this.deepClone(this.renewalCostList)
      const renewalCostList = renewalCostListClone.map(item => {
        item.costAccount = item.costAccount * 100
        return item
      })
      const dockingCostListClone: any = this.deepClone(this.dockingCostList)
      const dockingCostList = dockingCostListClone.map(item => {
        item.costAccount = item.costAccount * 100
        return item
      })

      const isInstallResult = this.checkFirstCostRule(this.firstCostEntities)
      if (isInstallResult.status === false) {
        this.jsonApiService.message(isInstallResult.message)
        return
      }

      if (this.contractForm.isOpenMaintainTax && !this.contractForm.maintainTax.tax) {
        this.jsonApiService.message('维修费电子发票信息不完整')
        return
      }
      if (this.contractForm.isOpenServiceTax && !this.contractForm.serviceTax.tax) {
        this.jsonApiService.message('续费/对接费电子发票信息不完整')
        return
      }

      if (!this.contractForm.isOpenMaintainTax) {
        this.contractForm.maintainTax = JSON.parse(JSON.stringify(this.contractFormBack.maintainTax))
      }
      if (!this.contractForm.isOpenServiceTax) {
        this.contractForm.serviceTax = JSON.parse(JSON.stringify(this.contractFormBack.serviceTax))
      }

      let reqdata = Object.assign(
        { ...this.contractForm },
        {
          firstCost: this.contractForm.firstCost * 100,
          renewalCost: this.contractForm.renewalCost * 100,
          outsideCost: this.contractForm.outsideCost * 100,
          firstCostEntities: JSON.stringify(isInstallResult.firstCostEntities),
          maintainTax: JSON.stringify(this.contractForm.maintainTax),
          serviceTax: JSON.stringify(this.contractForm.serviceTax),
          renewalCostList: JSON.stringify(renewalCostList),
          dockingCostList: JSON.stringify(dockingCostList)
        }
      )

      this.jsonApiService.http_obj('contractV2/recordChanges.html', reqdata).subscribe(data => {
        if (data.success) {
          this.closeProjectEventModal(modal)
          this.load()
        }
        this.jsonApiService.message(data.message)
      })
    }
  }
  // 删除
  delRow(row) {
    this.jsonApiService.confirm_message('此操作将永久删除数据,确认要删除?').then(() => {
      let reqdata = 'id=' + row.id
      this.jsonApiService.http('contractV2/deleteById.html', reqdata).subscribe(data => {
        this.jsonApiService.message(data.message)
        this.load()
      })
    })
  }
  /**
   * 图片的方法
   */
  imgList: any = []
  imgLocalList: any = []
  isViewer: boolean = false //默认隐藏
  isViewer1: boolean = false //默认隐藏
  //显示图片组件
  viewer1: any = ''
  imageInfo: any = {
    imageList: [],
    firstModelUrl: [],
    renewalModelUrl: [],
    describe: '合同模板'
  }

  //显示图片组件
  viewer: any = ''
  fileList: File = null

  bigImgClick(name) {
    // modal.show();
    if (this.isViewer && $('.viewer-container').length > 0) {
      this.viewer.destroy()
    }
    if (this.isViewer && $('.viewer-container').length > 0) {
      this.viewer.destroy()
      System.import('assets/js/viewer/viewer.js').then(() => {
        System.import('assets/js/viewer/bootstrap.bundle.min.js').then(() => {
          System.import('assets/js/viewer/viewer.css').then(() => {
            this.showImg(name)
          })
        })
      })
    } else {
      this.showImg(name)
    }
  }
  showImg(name) {
    var imgList = $('.' + name)[0]
    this.viewer = new Viewer(imgList, {
      url: 'src',
      title: function (image) {
        return image.alt + ' (' + (this.index + 1) + '/' + this.length + ')'
      }
    })
    this.isViewer = true
  }
  //上传多张
  multifileChange(files: FileList, modelUrl) {
    let multfileList = files
    var reqdata = new FormData()
    reqdata.append('describe', this.imageInfo.describe)
    reqdata.append('businessType', '3')
    reqdata.append('type', '2') //type 1获取相对路径  2获取绝对路径
    for (var i = 0; i < multfileList.length; i++) {
      this.fileList = multfileList[i]
      const isJPG =
        this.fileList.type === 'image/jpeg' || this.fileList.type === 'image/jpg' || this.fileList.type === 'image/png'
      if (!isJPG) {
        this.jsonApiService.message('上传图片只能是 png, jpg, jpeg 格式!')
        return
      }
      reqdata.append('files', multfileList[i])
    }
    this.jsonApiService.form_http('fileUpload/upload.html', reqdata).subscribe(data => {
      if (data.success) {
        this.imageInfo[modelUrl] = []
        for (var i = 0; i < data.data.length; i++) {
          this.imageInfo[modelUrl].push(data.data[i])
        }
      }
    })
    for (let k = 0; k < $('.up').length; k++) {
      $('.up')[k].value = null
    }
  }

  //删除图片
  deleteImg(index, i, modelUrl) {
    if (index == 1) {
      this.imageInfo[modelUrl].splice(i, 1)
    }
  }
}
